package com.sykj.util;

/**
 * Created by bingone on 15/12/16.
 */
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.converter.json.GsonBuilderUtils;

import com.google.gson.Gson;
import com.sun.tools.javah.resources.l10n;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 *
 * @author songchao
 * @since 2015-04-03
 */

public class JavaSmsApi1 {

    //查账户信息的http地址
    private  String URI_GET_USER_INFO =
        "https://sms.yunpian.com/v2/user/get.json";

    //智能匹配模板发送接口的http地址
    private  String URI_SEND_SMS =
        "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";
    
    private String AUTH_TOKEN = "71cc13188c2e4786bcedc73753bf759b";
    //模板发送接口的http地址
    private  String URI_TPL_SEND_SMS =
        "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";

    //发送语音验证码接口的http地址
    private  String URI_SEND_VOICE =
        "https://voice.yunpian.com/v2/voice/send.json";

    //绑定主叫、被叫关系的接口http地址
    private  String URI_SEND_BIND =
        "https://call.yunpian.com/v2/call/bind.json";

    //解绑主叫、被叫关系的接口http地址
    private  String URI_SEND_UNBIND =
        "https://call.yunpian.com/v2/call/unbind.json";

    //编码格式。发送编码格式统一用UTF-8
    private  String ENCODING = "UTF-8";
    
    //修改为您要发送的手机号
    static String mobile = "";
    
    public  String getMobile() {
		return mobile;
	}


	public  void setMobile(String mobile) {
		JavaSmsApi.mobile = mobile;
	}

	//   随机的验证码
    
    
    public static String randomCode() {
    	int suiji =  (int)((Math.random()*9+1)*100000);
        
        String shuijicode = suiji+"";
        return shuijicode;
    }
	
	
 //修改为您的apikey.apikey可在官网（http://www.yunpian.com)登录后获取
	private static String apikey = "39ca01770a374b729a846e640c3edcf0";
	
	
//	发送通知
	private  String Enter ="https://sms.yunpian.com/v2/sms/batch_send.json";
	
	

	public  String batchSend(String apikey, String text, String mobile) {
	    Map<String, String> params = new HashMap<String, String>();//请求参数集合
	    params.put("accountSid", apikey);
	    params.put("smsContent", text);
	    params.put("to", mobile);
	    params.put("templateid", "282453153");
	    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	    String format2 = format.format(new Date());
	    params.put("timestamp", format2 );
	    String md5 = MD5.encode(apikey+AUTH_TOKEN+format2 );
	    params.put("sig", md5 );
	    params.put("respDataType","JSON");
	    
	    return post("https://api.miaodiyun.com/20150822/industrySMS/sendSMS", params);//请自行使用post方式请求,可使用Apache HttpClient
	}
	
	
	public  void Regok()throws Exception{
		System.out.println(batchSend(apikey, "【小猪美颜社】您的账号已注册成功", mobile));
	}
	


    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws java.io.IOException
     */

    public  String getUserInfo(String apikey) throws IOException,
        URISyntaxException {
            Map < String, String > params = new HashMap < String, String > ();
            params.put("apikey", apikey);
            return post(URI_GET_USER_INFO, params);
        }
	/**
	 * 秒滴短信内容
	 * @return
	 */
	public String miaoDiSMS() {
		String temp = "【小猪科技】登录验证码：{1}，如非本人操作，请忽略此短信。";
		return temp;//String.format(temp, code);
	}
	public String miaoDiSMS1(String temp1) {
		String temp = "【小猪科技】小猪美颜社发送给您的信息{1}，请查收。";
		return temp;//String.format(temp, code);
	}
    /**
     * 智能匹配模板接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public  String sendSms(
        String mobile,String code) throws IOException {
    	Map<String, String> params = new HashMap<String, String>();//请求参数集合
	    params.put("accountSid", apikey);
	    System.out.println("模板："+miaoDiSMS());
	    params.put("smsContent", miaoDiSMS() );
	    params.put("param",code);
	    params.put("to", mobile);
	    params.put("templateid", "739204467");
	    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	    String format2 = format.format(new Date());
	    params.put("timestamp", format2 );
	    String md5 = MD5.encode(apikey+AUTH_TOKEN+format2 );
	    params.put("sig", md5 );
	    params.put("respDataType","JSON");
        return post(URI_SEND_SMS, params);
    }
    public  String sendSms1(
            String mobile,String code) throws IOException {
        	Map<String, String> params = new HashMap<String, String>();//请求参数集合
    	    params.put("accountSid", apikey);
    	    System.out.println("模板："+miaoDiSMS1(code));
    	    params.put("smsContent", miaoDiSMS1(code));
    	    params.put("param",code);
    	    params.put("to", mobile);
    	    params.put("templateid", "737222157");
    	    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    	    String format2 = format.format(new Date());
    	    params.put("timestamp", format2 );
    	    String md5 = MD5.encode(apikey+AUTH_TOKEN+format2 );
    	    params.put("sig", md5 );
    	    params.put("respDataType","JSON");
            return post(URI_SEND_SMS, params);
        }
    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey    apikey
     * @param tpl_id    　模板id
     * @param tpl_value 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public  String tplSendSms(String apikey, long tpl_id, String tpl_value,
        String mobile) throws IOException {
        Map < String, String > params = new HashMap < String, String > ();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tpl_id));
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

//    /**
//     * 通过接口发送语音验证码
//     * @param apikey apikey
//     * @param mobile 接收的手机号
//     * @param code   验证码
//     * @return
//     */
//
//    public static String sendVoice(String apikey, String mobile, String code) {
//        Map < String, String > params = new HashMap < String, String > ();
//        params.put("apikey", apikey);
//        params.put("mobile", mobile);
//        params.put("code", code);
//        return post(URI_SEND_VOICE, params);
//    }

//    /**
//     * 通过接口绑定主被叫号码
//     * @param apikey apikey
//     * @param from 主叫
//     * @param to   被叫
//     * @param duration 有效时长，单位：秒
//     * @return
//     */
//
//    public static String bindCall(String apikey, String from, String to,
//        Integer duration) {
//        Map < String, String > params = new HashMap < String, String > ();
//        params.put("apikey", apikey);
//        params.put("from", from);
//        params.put("to", to);
//        params.put("duration", String.valueOf(duration));
//        return post(URI_SEND_BIND, params);
//    }

//    /**
//     * 通过接口解绑绑定主被叫号码
//     * @param apikey apikey
//     * @param from 主叫
//     * @param to   被叫
//     * @return
//     */
//    public static String unbindCall(String apikey, String from, String to) {
//        Map < String, String > params = new HashMap < String, String > ();
//        params.put("apikey", apikey);
//        params.put("from", from);
//        params.put("to", to);
//        return post(URI_SEND_UNBIND, params);
//    }

    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public  String post(String url, Map < String, String > paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List < NameValuePair > paramList = new ArrayList <
                    NameValuePair > ();
                for (Map.Entry < String, String > param: paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(),
                        param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList,
                    ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
    public static void main(String[] args) throws URISyntaxException {
		JavaSmsApi1 j = new JavaSmsApi1();
		try {
			String sendSms = j.sendSms("13797745618",j.randomCode());
			System.out.println("**********"+j.randomCode()+"");
			Gson gson = new Gson();
			Map<String, Object> result = gson.fromJson(sendSms, HashMap.class);
			System.out.println(sendSms);
			System.out.println(result.get("respCode"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
